<?php

namespace Framework;


use App\Services\SignService;
use Closure;
use Illuminate\Http\Request;

class SignMiddleware
{
    use ErrorHelper;

    /**   第三方请求签名
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if (Hope::isProduct()) {
            return $next($request);
        }

        $params = $request->all();
        if (!array_key_exists('sign', $params)
            || !array_key_exists('sign_timestamp', $params)
            || !array_key_exists('sign_guid', $params)
            || !array_key_exists('sign_app_id',$params)
        ) {
            $this->retError("缺少签名参数");
        }
        $timestamp = $params['sign_timestamp'];
        $now = time();
        if (abs($now - $timestamp) > 60 * 10) {
            $this->retError("签名已过期");
        }
        $tmp_data = $params;
        unset($tmp_data['sign']);

        $sign_key = config('auth.open_sign.access_secret', 'f250c494-832e-78ba-b43d-a27ce1bf3c1b');
        $access_key = config('auth.open_sign.access_key', '7614bc75efd95b032f9d43064ad38b01');

        if($tmp_data['sign_app_id'] !== $access_key){
            $this->retError("appId不正确");
        }

        $sign = Hope::get_sign($tmp_data, $sign_key);

        if ($params['sign'] !== $sign) {
            $this->retError("签名错误");
        }
        return $next($request);
    }
}
